<template>
	<div id="chatlist">
		<ul v-for="message in messages" :key='message' >
			<div class='atalk' v-if="message.from == usernow"  >
			{{ message.context }} Send by 你
			</div>
			<div class='btalk' v-else  >
			{{ message.context }} Send by {{ message.from }}
			</div>
		</ul>
		<p > 当前用户为 {{ usernow }} </p>
		<textarea v-model='context' placeholder='内容'></textarea><br>
		<!--
		<input v-model='from' placeholder='来自'>
		-->
		<br>
		<button v-on:click='update()'>发送</button>
		<br>
		<button v-for="user in userlist" :key='user' v-on:click='changeuser(user)'> {{ user }} </button>
		<br>
		<input v-model='usertoadd' placeholder='用户名'>
		<button v-on:click='useradd(usertoadd)'>增加用户</button>
		<br>
		<input v-model='filename' placeholder='文件名'>
		<button @click="exportJSON(filename)">导出json</button>
		<br>
	</div>
</template>

<script>
import FileSaver from 'file-saver'

var fetch = function (key){
	return JSON.parse(window.sessionStorage.getItem(key)||'[]');
}
export default{
	name: 'chatlist',
	data: function (){
			return { messages: fetch('messages'),
					context: '',
					from: '',
					usernow: '',
					usertoadd: '',
					userlist: fetch('userlist'),
					filename: '',
			};	
	},
	watch:{
		messages:{
			handler:function(){
				//window.localStorage.setItem('messages',JSON.stringify(this.messages));
				this.save('messages',this.messages);
			},
			deep:true
		},
		userlist:{
			handler:function(){
				this.save('userlist',this.userlist);
			},
			deep:true
		}
	},
	methods: {
		update: function (){
			if (this.usernow == ''){
				alert("用户不能为空");
				return;
			}
			this.messages.push({context:this.context,
								from:this.usernow,
								sendtime:this.showtime()});
			//this.useradd(this.from);
			this.context = '';
		},
		useradd: function (user){
			if (this.userlist.includes(user)){
				alert("用户已经存在");
			}else if(user == ''){
				alert("用户名不能为空");
			}else {
				this.userlist.push(user);
				this.user = '';
			}
		},
		changeuser: function (usertochange){
			//this.useradd(usertochange);
			this.usernow = usertochange;
			this.usertochange = '';
		},
		exportJSON: function (filename){
			const data = JSON.stringify(this.messages)
			const blob = new Blob([data],{type: ''})
			FileSaver.saveAs(blob, filename+'.json')
		},
		showtime: function (){
			return new Date().toLocaleString();
		},
		save: function (key,item){
			window.sessionStorage.setItem(key,JSON.stringify(item));
		}
	},
}
</script>

<style>
#chatlist {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.atalk {
	color: #0000FF ;
}
.btalk {
	color: #FF0040;
}
</style>
